﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HanGu.Common;
using HanGu.Services.Interface;
using HanGu.CRM.Controllers;
using HanGu.Entity;

namespace HanGu.CRM.Areas.CustomerInfo.Controllers
{
    public class DefaultController : AdminBaseController
    {


        SelectList GetProvices(string proiceCode)
        {
            var provices = serviceArea.GetProvices();
            SelectList slist = new SelectList(provices, "AreaCode", "AreaName");
            if (string.IsNullOrEmpty(proiceCode))
            {
                proiceCode = provices != null && provices.Count > 0 ? provices[0].AreaCode : string.Empty;
            }
            ViewData["City"] = GetCitys(proiceCode);
            return slist;
        }

        SelectList GetCitys(string proiceCode)
        {
            var citys = serviceArea.GetCitys(proiceCode);
            SelectList slist = new SelectList(citys, "AreaCode", "AreaName");
            return slist;
        }

        SelectList GetMemberGrade()
        {
            SelectList selects = new SelectList(serviceDict.GetByGroupName("MemberGrade"), "GenerateKey", "Value");
            return selects;
        }

        /// <summary>
        /// 初始化 下拉列表
        /// </summary>
        /// <param name="proiceCode"></param>
        void GetSelectData(string proiceCode = null)
        {
            ViewData["SexList"] = GetListFromDict("sex", false);
            ViewData["IsMarry"] = GetListFromDict("marry", true);
            ViewData["Provice"] = GetProvices(proiceCode);
            ViewData["NativePlace"] = ViewData["Provice"];

            ViewData["Position"] = GetListFromDict("Position", false);
            ViewData["Job"] = GetListFromDict("Job", false);
            ViewData["Trade"] = GetListFromDict("Trade", false);
            ViewData["Interest"] = GetListFromDict("Interest");
            ViewData["MemberGrade"] = GetListFromDict("MemberGrade", false);
            ViewData["Degree"] = GetListFromDict("Degree", false);
            ViewData["Oganization"] = GetListFromDict("Oganization", false);
            ViewData["ImportantLevel"] = GetListFromDict("ImportantLevel", false);
            ViewData["Groups"] = new SelectList(serviceGroup.GetAll(), "ID", "GroupName");
            ViewData["Parents"] = new SelectList(GetManagersByLevel(false), "ID", "User");

        }

        public ActionResult Index()
        {
            SearchParma.IsBacklist = SearchParma.IsBacklist ?? false;
            SearchParma.HasChildren = SearchParma.HasChildren ?? false;
            SearchParma.IsPage = SearchParma.IsPage ?? true;
            ViewData["SexList"] = GetListFromDict("sex", true);
            ViewData["MemberGrade"] = GetListFromDict("MemberGrade", true);
            ViewData["Degree"] = GetListFromDict("Degree", true);
            string view = GetView();
            TempData["SearchParma"] = SearchParma;
            return View(view, GetMemberInfoList());
        }

        private string GetView()
        {
            string action = Request["action"];
            string view = "index";
            SearchParma.Pagination.IsPaging = true;
            SearchParma.IsPage = true;
            if (action == "selector")
            {
                view = "selector";
                SearchParma.Pagination.IsPaging = false;
                SearchParma.IsPage = false;
            }
            else if (action == "SelectorForGroup")
            {
                view = "SelectorForGroup";
                SearchParma.Pagination.IsPaging = false;
                SearchParma.IsPage = false;

            }

            return view;
        }

        public ActionResult HighSeach()
        {
            string optype = Request["optype"];
            bool isReset = (optype != null && optype == "reset");
            if (isReset)
            {
                SearchParma = new UniversallySearchParam();
            }
            SearchParma.IsBacklist = SearchParma.IsBacklist ?? false;
            SearchParma.HasChildren = SearchParma.HasChildren ?? false;
            SearchParma.IsPage = SearchParma.IsPage ?? true;
            RequestSearchParma();
            GetSelectData(SearchParma.Provice);
            if (isReset)
            {
                TempData["SearchParma"] = SearchParma;
            }
            return View();
        }

        void RequestSearchParma()
        {

            if (Request["IsBacklist"] != null)
            {
                SearchParma.IsBacklist = Request["IsBacklist"].IndexOf("true") >= 0;
            }
            SearchParma.Sex = Request["Sex"];
            SearchParma.Tel = Request["Tel"];
            SearchParma.NativePlace = Request["NativePlace"];
            SearchParma.IsMarry = Request["IsMarry"];

            if (Request["HasChildren"] != null)
            { SearchParma.HasChildren = Request["HasChildren"].IndexOf("true") >= 0; }
            SearchParma.Provice = Request["Provice"];
            SearchParma.City = Request["City"];
            SearchParma.Oganization = Request["Oganization"];
            decimal v = 0;
            if (decimal.TryParse(Request["ChargeRandS"], out v))
            {
                SearchParma.ChargeRandS = v;
            }
            v = 0;
            if (decimal.TryParse(Request["ChargeRandE"], out v))
            {
                SearchParma.ChargeRandE = v;
            }
            v = 0;
            if (decimal.TryParse(Request["ContractRandS"], out v))
            {
                SearchParma.ContractRandS = v;
            }
            v = 0;
            if (decimal.TryParse(Request["ContractRandE"], out v))
            {
                SearchParma.ContractRandE = v;
            }
            v = 0;
            if (decimal.TryParse(Request["ContractNumRandS"], out v))
            {
                SearchParma.ContractNumRandS = v;
            }
            v = 0;
            if (decimal.TryParse(Request["ContractNumRandE"], out v))
            {
                SearchParma.ContractNumRandE = v;
            }
            SearchParma.ImportantLevel = Request["ImportantLevel"];
            int assignedIn = 0;
            if (int.TryParse(Request["AssignedIn"], out assignedIn))
            {
                SearchParma.AssignedIn = assignedIn;
            }
            SearchParma.Groups = Request["memberGroups"];

            SearchParma.IsPage = Request["IsPage"] != null && Request["IsPage"].IndexOf("true") >= 0;

            string AssignedIns = Request["AssignedIns"];
            if (!string.IsNullOrEmpty(AssignedIns))
            {
                var assignedInList = new List<int>();
                int assigned = 0;
                foreach (var item in AssignedIns.Split(','))
                {
                    if (int.TryParse(item, out assigned))
                    {
                        assignedInList.Add(assigned);
                    }
                }
                if (assignedInList.Count > 0)
                {
                    SearchParma.SubAssignedIn = assignedInList;
                }
            }
            SearchParma.Trade = Request["Trades"];
            SearchParma.Position = Request["Positions"];
            SearchParma.Job = Request["Jobs"];
            SearchParma.Interest = Request["Interests"];
        }

        [HttpPost]
        public ActionResult Index(FormCollection collection)
        {
            ViewData["SexList"] = GetListFromDict("sex", true);
            ViewData["MemberGrade"] = GetListFromDict("MemberGrade", true);
            ViewData["Degree"] = GetListFromDict("Degree", true);

            SearchParma.Suitabler = Request["Suitabler"];
            SearchParma.Lectcher = Request["Lectcher"];
            SearchParma.PalayAdress = Request["PalayAdress"];
            SearchParma.Degree = Request["Degree"];
            SearchParma.Pagination.RowCount = null;
            RequestSearchParma();

            string view = GetView();
            TempData["SearchParma"] = SearchParma;
            return View(view, GetMemberInfoList());
        }

        List<HanGu.Entity.MemberInfo> GetMemberInfoList()
        {
            List<HanGu.Entity.MemberInfo> MemberInfoList = serviceMemberInfo.GetAll(base.SearchParma);
            ViewData["RowCount"] = SearchParma.Pagination.RowCount;
            return MemberInfoList;
        }

        public ActionResult Detail(int id)
        {
            string proviceCode = string.Empty;
            HanGu.Entity.MemberInfo memberInfo = new HanGu.Entity.MemberInfo() { Pwd = Helper.MD5(Helper.DEFAULTPWD), GUID = Helper.GetGuid, CreateTime = DateTime.Now, Creator = CurentUser.UserName, UpdateTime = DateTime.Now, Updater = CurentUser.UserName };
            if (id > 0)
            {
                memberInfo = serviceMemberInfo.GetByID(id);
                proviceCode = memberInfo.Provice;
            }

            GetSelectData(proviceCode);
            if (string.IsNullOrEmpty(memberInfo.PicPath))
            {
                memberInfo.PicPath = "/Content/default.jpg";
            }

            SearchParma.IntObj1 = memberInfo.ID;
            ViewData["ChangeCharge"] = serviceChangeCharge.GetAll(SearchParma);//改变积分
            //ViewData["ChangeGrade"] = serviceGrade.GetAll(SearchParma);
            //ViewData["ChargeProduct"] = serviceCharge.GetAll(SearchParma);//积分兑换
            GetJoinedGroups(memberInfo.ID);
            return View(memberInfo);
        }

        [HttpPost]
        public ActionResult Detail(int id, FormCollection collection)
        {
            string proviceCode = string.Empty;
            HanGu.Entity.MemberInfo memberInfo = new HanGu.Entity.MemberInfo() { Pwd = Helper.MD5(Helper.DEFAULTPWD), GUID = Helper.GetGuid, CreateTime = DateTime.Now, Creator = CurentUser.UserName, UpdateTime = DateTime.Now, Updater = CurentUser.UserName };
            if (id > 0)
            {
                memberInfo = serviceMemberInfo.GetByID(id);
                proviceCode = memberInfo.Provice;
            }

            GetSelectData(proviceCode);
            if (string.IsNullOrEmpty(memberInfo.PicPath))
            {
                memberInfo.PicPath = "/Content/default.jpg";
            }
            GetJoinedGroups(memberInfo.ID);
            return View("Create", memberInfo);
        }

        /// <summary>
        /// 获取客户加入的群
        /// </summary>
        /// <param name="memberid"></param>
        void GetJoinedGroups(int memberid)
        {
            if (memberid != 0)
            {
                var searchparameter = new UniversallySearchParam();
                searchparameter.IntObj2 = memberid;
                searchparameter.Pagination.IsPaging = false;
                var joinedGroups = serviceGroup.GetSelected(searchparameter);
                if (joinedGroups != null && joinedGroups.Count > 0)
                {
                    ViewData["MemberGroups"] = joinedGroups.Select(c => c.GroupID.ToString()).ToList<string>();
                }
            }
        }

        public ActionResult Create(int? id = null)
        {
            string proviceCode = string.Empty;
            HanGu.Entity.MemberInfo memberInfo = new HanGu.Entity.MemberInfo() { Pwd = Helper.MD5(Helper.DEFAULTPWD), GUID = Helper.GetGuid, CreateTime = DateTime.Now, Creator = CurentUser.UserName, UpdateTime = DateTime.Now, Updater = CurentUser.UserName, IsDirectly = false, IsNew = true, NoTel=true, NoSMS = true, NoEmail = true };
            if (id.HasValue && id.Value > 0)
            {
                memberInfo = serviceMemberInfo.GetByID(id.Value);
                proviceCode = memberInfo.Provice;
            }
            #region 判断非直属用户不可修改
            //if (memberInfo.MemberAssigneds != null && memberInfo.MemberAssigneds.FirstOrDefault(c => c.ManagerID == CurentUser.CurrentUserInfo.ID) == null)
            //{
            //    if (CurentUser.SubManager != null)//不是直属 仅可以查看
            //    {
            //        var managerSub = CurentUser.SubManager.Where(c => memberInfo.MemberAssigneds.FirstOrDefault(m => m.ManagerID == c.ID) != null).FirstOrDefault();
            //        if (managerSub != null)
            //        {
            //            if (!managerSub.IsDirectly.HasValue || !managerSub.IsDirectly.Value)
            //            {
            //                TempData["ErrorForIsDirectly"] = "不可以修改非直属下挂用户的客户信息";
            //                return RedirectToAction("Detail", new { id = id });
            //            }
            //        }
            //    }
            //}
            #endregion

            GetSelectData(proviceCode);
            if (string.IsNullOrEmpty(memberInfo.PicPath))
            {
                memberInfo.PicPath = "/Content/default.jpg";
            }

            GetJoinedGroups(memberInfo.ID);
            var autoOganization = serviceMemberInfo.GetOganization();
            if (autoOganization != null && autoOganization.Count > 0)
            {
                ViewData["AutoOganization"] = "['" + string.Join("','", autoOganization) + "']";
            }
            TempData["ChargeValue"] = memberInfo.Charge;
            return View(memberInfo);
        }

        //
        // POST: /MemberInfo/Create

        [HttpPost]
        [ValidateInput(false)]
        public string Create(FormCollection collection)
        {
            try
            {

                HanGu.Entity.MemberInfo memberInfo = new HanGu.Entity.MemberInfo();
                TryUpdateModel(memberInfo, collection);
                if (string.IsNullOrEmpty(memberInfo.RealName) || string.IsNullOrEmpty(memberInfo.Tel) || string.IsNullOrEmpty(Request["AssignedIns"]))
                {
                    ajaxStr = string.Format(ajaxStr, 300, ResourceManager.InvalidForms, navTabId, "", "");
                    return "{" + ajaxStr + "}";
                }
                if (memberInfo.ID > 0)
                {
                    memberInfo.Updater = base.CurentUser.UserName;
                    memberInfo.UpdateTime = DateTime.Now;
                }
                else
                {
                    memberInfo.CreateTime = DateTime.Now;
                    memberInfo.Creator = CurentUser.UserName;
                }
                if (!memberInfo.CreateTime.HasValue)
                {
                    memberInfo.CreateTime = DateTime.Now;
                }
                if (string.IsNullOrEmpty(memberInfo.Creator))
                {
                    memberInfo.Creator = CurentUser.UserName;
                }
                //memberInfo.NoEmail = collection["NoEmail"] != null;
                //memberInfo.NoSMS = collection["NoSMS"] != null;
                memberInfo.Interest = Request["Interest"];
                memberInfo.GroupID = Request["memberGroups"];
                memberInfo.Position = Request["Position"];
                memberInfo.Trade = Request["Trade"];
                memberInfo.Job = Request["Job"];
                memberInfo.SelectedMemberAssigneds = Request["AssignedIns"];
                memberInfo.OldParents = Request["OldParents"];
                bool tag = false;
                int memberid = memberInfo.ID;
                //子女信息
                var memberChildren = Session[memberid + "sMemberChildren"] as List<HanGu.Entity.MemberChildren>;
                memberChildren = memberChildren ?? new List<HanGu.Entity.MemberChildren>();
                memberChildren = memberChildren.Where(c => c.ID <= 0).ToList();
                //合同信息
                var memberContract = Session[memberid + "sMemberContract"] as List<HanGu.Entity.MemberContract>;
                memberContract = memberContract ?? new List<HanGu.Entity.MemberContract>();
                //联系记录
                var memberContact = Session[memberid + "sMemberContact"] as List<HanGu.Entity.vwMemberContact>;
                memberContact = memberContact ?? new List<HanGu.Entity.vwMemberContact>();
                //积分记录
                //var memberChargeRecord = Session[memberInfo.ID + "memberChargeRecord"] as List<HanGu.Entity.ChangeChargeRecorde>;
                //memberChargeRecord = memberChargeRecord ?? new List<HanGu.Entity.ChangeChargeRecorde>();

                #region 上传图片
                //if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
                //{
                //    if (Request.Files[0].ContentType.IndexOf("image") >= 0)
                //    {
                //        UploadFileManage uploadFile = new UploadFileManage(Request.Files[0]);
                //        uploadFile.ClassType = navTabId;
                //        uploadFile.Save();
                //        if (!uploadFile.Error)
                //        {
                //            //先删除旧图片
                //            if (!string.IsNullOrEmpty(memberInfo.PicPath))
                //            {
                //                uploadFile.DeleteFile(memberInfo.PicPath);
                //            }
                //            memberInfo.PicPath = uploadFile.FileInfo["filepath"];

                //        }
                //        else
                //        {
                //            ajaxStr = string.Format(ajaxStr, 300, uploadFile.Message, navTabId, "", "");
                //            return "{" + ajaxStr + "}";
                //        }
                //    }
                //    else
                //    { ajaxStr = string.Format(ajaxStr, 300, ResourceManager.UnusefulImag, navTabId, "", ""); return "{" + ajaxStr + "}"; }

                //}
                #endregion

                memberInfo.UserName = memberInfo.RealName;
                memberInfo.Pwd = Helper.MD5(Helper.DEFAULTPWD);
                memberInfo.IsChildren = memberChildren != null && memberChildren.Count > 0;

                memberInfo.ContractTotal = memberContract.Sum(c => c.Amount);
                memberInfo.ContractNum = memberContract.Count;
                memberContract = memberContract.Where(c => c.ID <= 0).ToList();
                if (memberInfo.ID > 0)
                {
                    tag = serviceMemberInfo.Update(memberInfo, memberChildren, memberContract, memberContact);
                }
                else
                {
                    tag = serviceMemberInfo.Add(memberInfo, memberChildren, memberContract, memberContact);
                }
                if (tag)
                {
                    ajaxStr = string.Format(ajaxStr, 200, ResourceManager.SaveSuccess, navTabId, "", "closeCurrent");
                    Session[memberid + "sMemberChildren"] = null;
                    Session[memberid + "sMemberContract"] = null;
                    Session[memberid + "sMemberContact"] = null;
                }
                else
                { ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", ""); }

            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");
            }
            return "{" + ajaxStr + "}";
        }

        //
        // GET: /MemberInfo/Delete/5
        [HttpPost]
        public string Delete(int id, string guid)
        {
            try
            {
                try
                {
                    FileManageController filemanage = new FileManageController();
                    filemanage.DeleteExecute(guid);
                }
                catch { }
                serviceMemberInfo.Delete(id);
                ajaxStr = string.Format(ajaxStr, 200, ResourceManager.DeleteSuccess, navTabId, "", "");
            }
            catch (Exception ex)
            {
                ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.DeleteFail, navTabId, "", "");
            }

            return "{" + ajaxStr + "}";

        }

        [HttpPost]
        public string ResetPWD(int id, string guid)
        {
            try
            {
                var memberInfo = serviceMemberInfo.GetByID(id);
                if (!string.IsNullOrEmpty(memberInfo.UserName) && !string.IsNullOrEmpty(memberInfo.Email))
                {
                    int result = serviceMemberInfo.IsResetPwd(memberInfo.UserName, memberInfo.Email);
                    switch (result)
                    {
                        case -1:
                            ajaxStr = string.Format(ajaxStr, 300, "重设失败,请联系管理员", "", "", "");
                            break;
                        case 0:

                            SendMessage send = new SendMessage(true, true);
                            List<string> EmailTo = new List<string>();
                            EmailTo.Add(memberInfo.Email);
                            List<string> SMSTo = new List<string>();
                            SMSTo.Add(memberInfo.Tel);
                            send.EmailTo = EmailTo;
                            send.EmailCC = new List<string>();
                            send.SMSTo = SMSTo;
                            send.Title = "重设密码";
                            send.Content = string.Format("尊敬的：{0}，您的用户名是：{1}，密码是：{2}，请您妥善保管！",
                                          memberInfo.RealName,
                                          memberInfo.UserName,
                                          Helper.DEFAULTPWD
                                          );
                            if (send.SendAll())
                            {
                                ajaxStr = string.Format(ajaxStr, 200, "重设且发送成功", "", "", "");
                            }
                            else
                            {
                                ajaxStr = string.Format(ajaxStr, 300, "重设成功，但发送失败，请检查邮件接口或短信接口设置是否正确。", "", "", "");
                            }
                            break;
                        case 1:
                            ajaxStr = string.Format(ajaxStr, 300, "重设失败,用户名与邮箱不匹配", "", "", "");

                            break;
                        case 2:
                            ajaxStr = string.Format(ajaxStr, 300, "重设失败,请联系管理员", "", "", "");
                            break;
                        default:
                            ajaxStr = string.Format(ajaxStr, 300, "重设失败,请联系管理员", "", "", "");
                            break;
                    }
                }


            }
            catch (Exception ex)
            {
                ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.DeleteFail, navTabId, "", "");
            }

            return "{" + ajaxStr + "}";

        }

        public string TelExitsed(int id)
        {
            bool result = false;
            string tel = Request["Tel"];
            result = !serviceMemberInfo.TelExitsed(id, tel);
            return result.ToString().ToLower();
        }
    }
}
